#!/bin/bash

# Source the platform_utils script
source "$(dirname "$0")/platform_utils" > /dev/null 2>&1

${SMARTSWITCH:=false}

# Restrict command to sudo users
if [ "$EUID" -ne 0 ] ; then
  echo "Root priveleges are needed for this operation"
  exit 1
fi

if [ -f /etc/sonic/chassisdb.conf ] && [ "$SMARTSWITCH" = false ] ; then
  CHASSIS_TSA_STATE_UPDATE="CHASSIS_APP_DB HMSET "BGP_DEVICE_GLOBAL\|STATE" tsa_enabled "false""
  CONFIG_DB_TSA_STATE_UPDATE='{"BGP_DEVICE_GLOBAL":{"STATE":{"tsa_enabled": "false"}}}'
  current_tsa_state="$(sonic-cfggen -d -v BGP_DEVICE_GLOBAL.STATE.tsa_enabled)"
  if [[ $current_tsa_state  == false ]]; then
    echo "Chassis is already in Normal mode"
    logger -t TSB -p user.info "Chassis is already in Normal mode"
  else
    sonic-db-cli $CHASSIS_TSA_STATE_UPDATE
    sonic-cfggen -a "$CONFIG_DB_TSA_STATE_UPDATE" -w
    echo "Chassis Mode: Maintenance -> Normal"
    logger -t TSB -p user.info "Chassis Mode: Maintenance -> Normal"
  fi
  echo "Please execute 'sudo config save' to preserve System mode in Normal state after reboot\
  or config reload on all linecards"
  exit 0
fi

# toggle the mux to auto if dualtor
if [[ "$(sonic-cfggen -d -v DEVICE_METADATA.localhost.subtype | tr '[:upper:]' '[:lower:]')" == *"dualtor"* ]];
then
  logger -t TSB -p user.info "Toggle all mux mode to auto"
  sudo config mux mode auto all
fi

if [ -z "$STARTED_BY_TSA_TSB_SERVICE" ]; then
  service='startup_tsa_tsb.service'
  if [[ $(/bin/systemctl show $service --property ActiveState  --value) == "active" ]] && \
     [[ $(/bin/systemctl show $service --property SubState  --value) == "running" ]]; then
      echo "Stopping $service before configuring TSB"
      systemctl stop $service
      if sonic-db-cli STATE_DB HDEL "ALL_SERVICE_STATUS|tsa_tsb_service" "running" >/dev/null; then
        echo "Successfully removed TSA-TSB service flag."
      else
        echo "Failed to remove TSA-TSB service flag!" >&2
      fi
  fi
fi

/usr/bin/TS TSB
if [[ "$(sonic-cfggen -d -v DEVICE_METADATA.localhost.type)" == *"SpineRouter"* ]] ; then
  if [[ "$1" != "chassis" ]] ; then
    echo "Please execute 'sudo config save' to preserve System mode in Normal state after reboot or config reload"    
  fi
else
  echo "Please execute 'sudo config save' to preserve System mode in Normal state after reboot or config reload"
fi
